package cn.tom.controller;

import cn.tom.entity.ExportVo;
import cn.tom.entity.P1;
import cn.tom.entity.Usr;
import cn.tom.service.LargeFileService;
import cn.tom.service.P1Service;
import cn.tom.service.UserService;
import cn.tom.tool.Token;
import cn.tom.tool.XJson;
import cn.tom.tool.XResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

@RequestMapping({"/api/public"})
@RestController
public class PublicController {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    LargeFileService largeFileService;

    @Autowired
    UserService userService;

    @Autowired
    P1Service p1Service;

    @PostMapping("/findOther/{start}/{num}")
    public XJson findAll(@PathVariable("start") Integer start, @PathVariable("num") Integer num, String name1,Integer categoryId,String leader,String startDate,String estimateDate) throws IllegalAccessException {
        System.out.println("start=" + start +  "&&" + "num=" + num);
        System.out.println("name1=" + name1 +  "&&" + "categoryId=" + categoryId);
        System.out.println("leader=" + leader +  "&&" + "startDate=" + startDate + "&&" + "estimateDate=" + estimateDate);
        Map<String,Object> map = new HashMap<>();
        Integer start2 = (start - 1) * num;
        map.put("start",start2);
        map.put("num",num);

        map.put("name1",name1);
        map.put("categoryId", categoryId);
        map.put("leader",leader);
        map.put("startDate",startDate);
        map.put("estimateDate",estimateDate);


        List<ExportVo> p2 = p1Service.findByOther(map);
        return XResp.pack(200,"" ,p2);
    }

    @GetMapping({"/findPage/{start}/{num}/{typeid}"})
    public XJson findPages_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        this.log.info("==========/findPageBook/{start}/{num}/{typeid}   start=" + start + "  num=" + num + "  typeid=" + typeid);
        Map<String, Object> map = new HashMap<>();
        Integer start2 = (start - 1) * num;
        /*map.put("books", this.bookService.findPageType(start2,num,typeid));
        map.put("total", this.bookService.getCountType(typeid));*/
        return XResp.pack(200, "", map);
    }

    @GetMapping("/checkToken")
    public XJson checkToken( ) {
        log.info("checkToken");
        int uid = -1;
        uid = Token.getUid();
        if (uid < 0) {
            return XResp.pack(401, "token失效", null);
        }
        return XResp.pack(200, "token有效", null);
    }
    @GetMapping({"/showimg/{id}"})
    public void dispaly(@PathVariable("id") String id, HttpServletResponse response) {
        byte[] buf;
        if (id != null) {
            try {
                buf = (byte[]) this.largeFileService.findOne(id).getContent();
            } catch (NullPointerException e) {
                buf = new byte[1];
            }
            try {
                response.setContentType("image/jpeg");
                response.getOutputStream().write(buf);
                response.flushBuffer();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
    @PostMapping({"/addUser"})
    public XJson addUser(@RequestParam(value = "mypic", required = false) MultipartFile file, Usr u) throws IOException {
        this.log.info("file=" + file);
        this.log.info("================添加用户=" + u);
        if (this.userService.findByAccount(u.getAccount()) != null) {
            return XResp.pack(200, "注册失败， 账号重复", null);
        }
        if (file != null && file.getSize() > 0) {
            if (u.getImg() != null) {
                this.largeFileService.delete(u.getImg());
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            u.setImg(uuid);
            this.largeFileService.add(uuid, file.getOriginalFilename(), file.getBytes());
        }
        u.setRole("usr");
        this.userService.add(u);
        u.setPassword("");
        return XResp.pack(200, "注册成功 ...", u);
    }
}
